package com.bangcommunity.bbframe.mlog;

import com.bangcommunity.bbframe.common.base.MainConfigLoader;
import com.bangcommunity.bbframe.mlog.collector.StatisticStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tanghc
 * @date 18/1/25
 */
public abstract class MLog {
    static Logger logger = LoggerFactory.getLogger(MLog.class);
    static MainConfigLoader mainConfigLoader = MainConfigLoader.getInstance();

    public static void start(String parentTxid, String key, String bizKey, Object[] args) {
        try {
            String mkey = createMkey(key);
            MLogClient.start(parentTxid, mkey, bizKey, args);
        } catch (Exception e) {
            logger.error("mlog start error:{}",e.getMessage());
        }
    }

    public static String createMkey(String key) {

        return new StringBuilder().append(mainConfigLoader.getProductCode()).append("_")
                .append(mainConfigLoader.getAppCode()).append("_").append(key).toString();
    }

    public static void exception(String key, Throwable throwable) {
        finish(key, StatisticStateEnum.exception, null, throwable);
    }

    public static void finish(String key, StatisticStateEnum stateEnum, Object result, Throwable throwable) {
        try {
            String mkey = createMkey(key);
            MLogClient.finish(mkey, stateEnum, result, throwable);
        } catch (Exception e) {
            logger.error("mlog finish error:{}",e.getMessage());
        }

    }

    public static void succ(String key, Object result) {
        finish(key, StatisticStateEnum.succ, result, null);
    }

    public static void fail(String key, Object result) {
        finish(key, StatisticStateEnum.fail, result, null);
    }
}
